#include "doctorfunctionwidget.h"
#include <QVBoxLayout>
#include <QWidget>
#include <QDebug>
#include <QLabel>
#include <QFormLayout>
#include <QTreeWidget>
#include <QStackedWidget>
#include <QPushButton>
#include"../AppointmentRegister/Server/appointment/doctot_communication.h"

doctorFunctionWidget::doctorFunctionWidget( int currentID, QString role,QWidget *parent) : QWidget(parent) {

    this->currentID = currentID;
    this->role = role;

    QWidget::setWindowTitle("DOCTOR");
    resize(800,600);
    // 创建主布局
    QHBoxLayout *mainLayout = new QHBoxLayout(this);

    // 创建侧边菜单
        QVBoxLayout *sidebarLayout = new QVBoxLayout();

        // 头像显示部分
           QLabel *avatarLabel = new QLabel(this);
           QPixmap avatarPixmap(":/images/avatar.png");  // 假设你有一个 avatar.png 图片
           avatarLabel->setPixmap(avatarPixmap.scaled(80, 80, Qt::KeepAspectRatio));  // 设置头像大小
           avatarLabel->setAlignment(Qt::AlignCenter);

           sidebarLayout->addWidget(avatarLabel);  // 添加头像到布局
           sidebarLayout->addSpacing(10);  // 添加间隔，避免头像与菜单重叠

    // 创建侧边菜单
    QTreeWidget *sidebarMenu = new QTreeWidget(this);
    sidebarMenu->setHeaderLabel("功能菜单");
    sidebarMenu->setFixedWidth(200); // 设置侧边菜单宽度
     sidebarMenu->setStyleSheet("QTreeWidget { background-color: #f0f0f0; border: none; }");  // 设置菜单背景


    // 添加功能菜单项
    QTreeWidgetItem *viewAppointments = new QTreeWidgetItem(sidebarMenu, QStringList() << "查看预约");
    QTreeWidgetItem *editProfile = new QTreeWidgetItem(sidebarMenu, QStringList() << "编辑个人信息");
//    QTreeWidgetItem *editCases = new QTreeWidgetItem(sidebarMenu, QStringList() << "编辑病例");
    QTreeWidgetItem *communication = new QTreeWidgetItem(sidebarMenu, QStringList() << "医患沟通");

    sidebarLayout->addWidget(sidebarMenu);  // 将侧边菜单添加到布局中


    // 创建内容显示区
    stackedWidget = new QStackedWidget(this);
//    mainLayout->addWidget(stackedWidget); // 将堆叠窗口添加到布局中

    // 添加各个页面
    stackedWidget->addWidget(createAppointmentPage()); // 查看预约页面
    stackedWidget->addWidget(createProfilePage()); // 编辑个人信息页面
//    stackedWidget->addWidget(createCasesPage()); // 编辑病例页面
     doctot_communication *communicationPage = new doctot_communication();
//         qDebug()<<"+++++++++++++++++++++++++++++++++++++++";
////    stackedWidget->addWidget(createCommunicationPage()); // 医患沟通页面
    stackedWidget->addWidget(communicationPage); // 医患沟通页



    // 连接侧边菜单的信号
    connect(sidebarMenu, &QTreeWidget::itemClicked, this, [this, sidebarMenu](QTreeWidgetItem *item, int) {
        if (item == sidebarMenu->topLevelItem(0)) {
            fetchAppointments();
            stackedWidget->setCurrentIndex(0); // 查看预约
        } else if (item == sidebarMenu->topLevelItem(1)) {
            fetchDoctorProfile();
            stackedWidget->setCurrentIndex(1); // 编辑个人信息
        } else if (item == sidebarMenu->topLevelItem(2)) {
            stackedWidget->setCurrentIndex(2); // 编辑病例
        } else if (item == sidebarMenu->topLevelItem(3)) {
            stackedWidget->setCurrentIndex(3); // 医患沟通
        }
    });

    // 创建退出登录按钮
    QPushButton *logoutButton = new QPushButton("退出登录", this);
    logoutButton->setStyleSheet("QPushButton { background-color: #ff4d4d; color: white; border-radius: 5px; font-weight: bold; padding: 10px; }"
                                   "QPushButton:hover { background-color: #e60000; }");  // 设置按钮样式
//    mainLayout->addWidget(logoutButton);
    connect(logoutButton, &QPushButton::clicked, this, &doctorFunctionWidget::logout);

    // 设置退出按钮的位置
       QSpacerItem *spacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
       sidebarLayout->addItem(spacer);  // 将退出按钮放置在底部

       sidebarLayout->addWidget(logoutButton);  // 将退出按钮添加到布局中

       // 将侧边菜单布局和内容显示区布局添加到主布局
          mainLayout->addLayout(sidebarLayout);
          mainLayout->addWidget(stackedWidget);  // 将堆叠窗口添加到布局中

    // 设置布局
    setLayout(mainLayout);
}

doctorFunctionWidget::~doctorFunctionWidget()
{
}

QWidget* doctorFunctionWidget::createAppointmentPage() {
    QWidget *appointmentWidget = new QWidget(this);
    QVBoxLayout *appointmentLayout = new QVBoxLayout(appointmentWidget);

    // 初始化预约信息表单
    appointmentTable = new QTableWidget(this);
    appointmentTable->setColumnCount(3);
    appointmentTable->setHorizontalHeaderLabels({"患者姓名", "预约时间", "Status"});

    appointmentLayout->addWidget(appointmentTable);
    // 连接点击事件
    connect(appointmentTable, &QTableWidget::cellClicked, this, &doctorFunctionWidget::onAppointmentItemClicked);

    fetchAppointments();
    return appointmentWidget;
}

QWidget* doctorFunctionWidget::createProfilePage() {
    QWidget *profileWidget = new QWidget(this);
    QVBoxLayout *profileLayout = new QVBoxLayout(profileWidget);

    // 创建头像显示区域
    QGroupBox *avatarGroup = new QGroupBox("头像", this);
    QVBoxLayout *avatarLayout = new QVBoxLayout(avatarGroup);
    avatarLabel = new QLabel(this);
    avatarLayout->addWidget(avatarLabel);
    profileLayout->addWidget(avatarGroup);

    // 创建个人信息表单
    QGroupBox *infoGroup = new QGroupBox("个人信息", this);
    QFormLayout *infoLayout = new QFormLayout(infoGroup);

    usernameEdit = new QLineEdit(this);
    infoLayout->addRow("用户名", usernameEdit);

    passwordEdit = new QLineEdit(this);
    passwordEdit->setEchoMode(QLineEdit::Password);
    infoLayout->addRow("密码", passwordEdit);

    nameEdit = new QLineEdit(this);
    infoLayout->addRow("姓名", nameEdit);

    phoneEdit = new QLineEdit(this);
    infoLayout->addRow("联系电话", phoneEdit);

    specializationEdit = new QLineEdit(this);
    infoLayout->addRow("专业", specializationEdit);

    departmentEdit = new QLineEdit(this);
    infoLayout->addRow("部门", departmentEdit);

    titleEdit = new QLineEdit(this);
    infoLayout->addRow("标题", titleEdit);

    introductionEdit = new QLineEdit(this);
    infoLayout->addRow("个人介绍", introductionEdit);

    profileLayout->addWidget(infoGroup);

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();

    QPushButton *saveButton = new QPushButton("保存", this);
    connect(saveButton, &QPushButton::clicked, this, &doctorFunctionWidget::onSaveClicked);
    buttonLayout->addWidget(saveButton);

//    QPushButton *exitButton = new QPushButton("退出", this);
//    connect(exitButton, &QPushButton::clicked, this, &doctorFunctionWidget::onExitClicked);
//    buttonLayout->addWidget(exitButton);

    profileLayout->addLayout(buttonLayout);

    // 获取当前登录用户的个人信息
    fetchDoctorProfile();

    return profileWidget;
}

QWidget* doctorFunctionWidget::createCasesPage() {
    QWidget *casesWidget = new QWidget(this);
    QVBoxLayout *casesLayout = new QVBoxLayout(casesWidget);

    // 创建病例表单
    caseTable = new QTableWidget(this);
    caseTable->setColumnCount(2);
    caseTable->setHorizontalHeaderLabels({"预约", "患者姓名"});
    casesLayout->addWidget(caseTable);

    // 连接病例表单的点击事件
    connect(caseTable, &QTableWidget::cellClicked, this, &doctorFunctionWidget::onCaseItemClicked);
    // 创建写医嘱页面
    prescriptionWidget = new QWidget(this);
    QVBoxLayout *prescriptionLayout = new QVBoxLayout(prescriptionWidget);

    patientNameLabel = new QLabel(prescriptionWidget);
    appointmentTimeLabel = new QLabel(prescriptionWidget);
    treatmentStatusLabel = new QLabel(prescriptionWidget);
    prescriptionTextEdit = new QTextEdit(prescriptionWidget);
    savePrescriptionButton = new QPushButton("保存医嘱", prescriptionWidget);

    prescriptionLayout->addWidget(patientNameLabel);
    prescriptionLayout->addWidget(appointmentTimeLabel);
    prescriptionLayout->addWidget(treatmentStatusLabel);
    prescriptionLayout->addWidget(prescriptionTextEdit);
    prescriptionLayout->addWidget(savePrescriptionButton);

    connect(savePrescriptionButton, &QPushButton::clicked, this, &doctorFunctionWidget::onSavePrescriptionClicked);

    // 将写医嘱页面添加到堆叠窗口
    stackedWidget->addWidget(prescriptionWidget);


    return casesWidget;
}

QWidget* doctorFunctionWidget::createCommunicationPage() {
    QWidget *communicationWidget = new QWidget(this);
    QVBoxLayout *communicationLayout = new QVBoxLayout(communicationWidget);
    QLabel *communicationLabel = new QLabel("医患沟通", communicationWidget);
    communicationLayout->addWidget(communicationLabel);


    return communicationWidget;
}

void doctorFunctionWidget::onCurrentItemChanged(const int &index) {
    // 处理侧边栏项变化
    qDebug() << "Current item changed to:" << index;
    // 在这里可以根据 index 切换不同的功能界面
    stackedWidget->setCurrentIndex(index);
}

void doctorFunctionWidget::onCaseItemClicked(int row, int column) {
    // 处理病例表单项点击事件
    qDebug() << "Case item clicked at row:" << row << "column:" << column;

    // 获取点击的患者姓名
    QString patientName = caseTable->item(row, 0)->text();
    QString patientNumber = caseTable->item(row, 1)->text();

    // 创建一个新的治疗窗口
    treatmentPage = new treatmentWidget(this);
    stackedWidget->addWidget(treatmentPage);
    stackedWidget->setCurrentWidget(treatmentPage);

    // 给治疗页面传预约号和姓名
    treatmentPage->setPatientInfo(patientName, patientNumber);
}

void doctorFunctionWidget::onSearchClicked() {
    // 获取搜索输入框中的预约号
    QString appointmentNumber = searchLineEdit->text();

    // 发送查询请求到服务器
    QString sql = QString("SELECT * FROM Appointments WHERE AppointmentNumber = '%1'").arg(appointmentNumber);
    tcp->sendMsg(sql);

    // 连接服务器的响应信号
    connect(tcp->socket, &QTcpSocket::readyRead, [=]() {
        QByteArray response = tcp->socket->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
        QJsonArray jsonArray = jsonDoc.array();

        if (jsonArray.isEmpty()) {
            QMessageBox::warning(this, "查询失败", "未找到对应的预约信息！");
        } else {
            // 清空表格
            appointmentTable->setRowCount(0);

            // 填充表格
            for (const QJsonValue &value : jsonArray) {
                QJsonObject obj = value.toObject();
                int row = appointmentTable->rowCount();
                appointmentTable->insertRow(row);
                appointmentTable->setItem(row, 0, new QTableWidgetItem(obj["AppointmentNumber"].toString()));
                appointmentTable->setItem(row, 1, new QTableWidgetItem(obj["PatientName"].toString()));
                appointmentTable->setItem(row, 2, new QTableWidgetItem(obj["AppointmentTime"].toString()));
            }
        }
    });
}

//保存信息
void doctorFunctionWidget::onSaveClicked() {
    // 获取修改后的个人信息
    QString username = usernameEdit->text();
    QString password = passwordEdit->text();
    QString name = nameEdit->text();
    QString phone = phoneEdit->text();
    QString specialization = specializationEdit->text();
    QString department = departmentEdit->text();
    QString title = titleEdit->text();
    QString introduction = introductionEdit->text();

    // 构建更新 SQL 语句
    QString sql = QString("UPDATE Doctors SET Username='%1', Password='%2', Name='%3', ContactNumber='%4', Specialization='%5', Department='%6', Title='%7', Introduction='%8' WHERE DoctorID=%9")
            .arg(username).arg(password).arg(name).arg(phone).arg(specialization).arg(department).arg(title).arg(introduction).arg(currentID);
    tcp=new ClientTcp(INSERT_DATA);
    // 发送更新请求到服务器
    tcp->sendMsg(sql);

    //      // 连接服务器的响应信号
    //         connect(tcp->socket, &QTcpSocket::readyRead, [=]() {
    //             tcp->onInsertData(); // 调用 onInsertData 函数处理服务器响应

    //             if (tcp->getFlag()) {
    //                 QMessageBox::information(this, "保存成功", "个人信息已成功保存！");
    //             } else {
    //                 QMessageBox::warning(this, "保存失败", "个人信息保存失败！");
    //             }
    //         });
}

//void doctorFunctionWidget::onExitClicked() {
//    // 退出当前页面
//}

void doctorFunctionWidget::logout() {
    // 在这里添加退出登录的逻辑，比如清除用户信息、返回登录页面等
    // 例如：this->close(); 或者跳转到登录页面
    QMessageBox::StandardButton reply;
          reply = QMessageBox::question(this, "退出登录", "确认退出登录吗?",
                                        QMessageBox::Yes | QMessageBox::No);
          if (reply == QMessageBox::Yes) {
              // 清除用户数据（例如清除会话、缓存、设置等）
              // 跳转到登录页面
              emit doctorLoggedOut();
              // 或者直接关闭当前页面
              this->close();
          }
}
//表单点击槽函数
void doctorFunctionWidget::onAppointmentItemClicked(int row, int column)
{
    // 处理预约表单项点击事件
    qDebug() << "Appointment item clicked at row:" << row << "column:" << column;

    // 获取点击的患者姓名、预约时间和治疗情况
    QString patientName = appointmentTable->item(row, 0)->text();
    QString appointmentTime = appointmentTable->item(row, 1)->text();
    QString treatmentStatus = appointmentTable->item(row, 2)->text();

    // 设置患者信息到写医嘱页面
    patientNameLabel->setText("患者姓名: " + patientName);
    appointmentTimeLabel->setText("预约时间: " + appointmentTime);
    treatmentStatusLabel->setText("治疗情况: " + treatmentStatus);

    // 切换到写医嘱页面
    stackedWidget->setCurrentWidget(prescriptionWidget);
}

void doctorFunctionWidget::onSavePrescriptionClicked()
{
    QString prescription = prescriptionTextEdit->toPlainText();
    // 在这里处理保存医嘱的逻辑
    QMessageBox::information(this, "保存成功", "医嘱已保存！");
}

//在页面显示用户信息
void doctorFunctionWidget::setDoctorProfile() {
    // 设置个人信息到对应的 QLineEdit 和 QLabel
    usernameEdit->setText(doctorProfile["Username"].toString());
    passwordEdit->setText(doctorProfile["Password"].toString());
    nameEdit->setText(doctorProfile["Name"].toString());
    phoneEdit->setText(doctorProfile["ContactNumber"].toString());
    specializationEdit->setText(doctorProfile["Specialization"].toString());
    departmentEdit->setText(doctorProfile["Department"].toString());
    titleEdit->setText(doctorProfile["Title"].toString());
    introductionEdit->setText(doctorProfile["Introduction"].toString());

    // 设置头像
    QString avatarPath = doctorProfile["AvatarPath"].toString();
    QPixmap avatar(avatarPath);
    avatarLabel->setPixmap(avatar.scaled(100, 100, Qt::KeepAspectRatio));
}

//从数据库中Doctors查找用户的信息
void doctorFunctionWidget::fetchDoctorProfile() {
    tcp=new ClientTcp(DOCTORS_DATA);
    // 构建查询 SQL 语句
    QString sql = QString("SELECT DoctorID, Name, ContactNumber, Specialization, Experience, Department, Title, Introduction, AvatarPath, Username, Password, Role FROM Doctors WHERE DoctorID = %1").arg(currentID);
    // 发送查询请求到服务器
    tcp->sendMsg(sql);
    connect(tcp->socket, &QTcpSocket::readyRead, [=]() {
        // 获取医生的个人信息
        const QList<QJsonObject> &doctorData = tcp->getDoctorsData();

        if (!doctorData.isEmpty()) {
            const QJsonObject &doctor = doctorData.first();
            qDebug() << "Doctor Data:" << doctor;
            // 将获取到的个人信息存储到成员变量中
            doctorProfile["DoctorID"] = doctor["DoctorID"].toInt();
            doctorProfile["Name"] = doctor["Name"].toString();
            doctorProfile["ContactNumber"] = doctor["ContactNumber"].toString();
            doctorProfile["Specialization"] = doctor["Specialization"].toString();
            doctorProfile["Experience"] = doctor["Experience"].toInt();
            doctorProfile["Department"] = doctor["Department"].toString();
            doctorProfile["Title"] = doctor["Title"].toString();
            doctorProfile["Introduction"] = doctor["Introduction"].toString();
            doctorProfile["AvatarPath"] = doctor["AvatarPath"].toString();
            doctorProfile["Username"] = doctor["Username"].toString();
            doctorProfile["Password"] = doctor["Password"].toString();
            doctorProfile["Role"] = doctor["Role"].toString();

            // 设置个人信息到对应的 QLineEdit 和 QLabel
            setDoctorProfile();

        } else {
            QMessageBox::warning(this, "查询失败", "未找到对应的医生信息！");
        }
    });
}

void doctorFunctionWidget::fetchAppointments()
{

    // 构建查询 SQL 语句  AppointmentID, PatientID,DoctorID,AppointmentDate,Status,
//    QString sql = QString("SELECT Users.Name AS PatientName, Appointments.AppointmentDate, Appointments.Status "
//                          "FROM Appointments JOIN Users ON Appointments.PatientID = Users.UserID WHERE Appointments.DoctorID = 1;").arg(currentID);
    QString sql = QString("SELECT Appointments.AppointmentID, Appointments.PatientID, Appointments.DoctorID, Appointments.AppointmentDate, Appointments.Status, Users.Name AS PatientName"
                          " FROM Appointments JOIN Users ON Appointments.PatientID = Users.UserID WHERE Appointments.DoctorID = 1;").arg(currentID);
    tcp_APP=new ClientTcp(APPOINTMENTS_DATA_2);
    // 发送查询请求到服务器
    tcp_APP->sendMsg(sql);
    // 连接服务器的响应信号
    connect(tcp_APP->socket, &QTcpSocket::readyRead, [=]() {

        // 获取预约的信息
        const QList<QJsonObject> &appointData = tcp_APP->getAppointmentsData();

        if (!appointData.isEmpty()) {
            // 清空表格
            appointmentTable->setRowCount(0);

            // 填充表格
            for (const QJsonObject &appointment : appointData) {
                int row = appointmentTable->rowCount();
                appointmentTable->insertRow(row);
                appointmentTable->setItem(row, 0, new QTableWidgetItem(appointment["PatientName"].toString()));
                appointmentTable->setItem(row, 1, new QTableWidgetItem(appointment["AppointmentDate"].toString()));
                appointmentTable->setItem(row, 2, new QTableWidgetItem(appointment["Status"].toString()));
            }
        } else {
            QMessageBox::warning(this, "查询失败", "未找到对应的预约信息！");
        }
    });
}
